package me.zingon.self.bigdispatcher.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import me.zingon.self.bigdispatcher.constant.JOB_STATUS;
import me.zingon.self.bigdispatcher.constant.JobDataKey;
import me.zingon.self.bigdispatcher.dao.NacosJobDao;
import me.zingon.self.bigdispatcher.entity.NacosJob;
import me.zingon.self.bigdispatcher.job.NacosJobDetail;
import me.zingon.self.bigdispatcher.service.NacosJobService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * (NacosJobDetail)表服务实现类
 *
 * @author zingon
 * @since 2020-12-30 10:35:25
 */
@Slf4j
@Service("nacosJobService")
public class NacosJobServiceImpl implements NacosJobService {
    @Autowired
    private NacosJobDao nacosJobDao;

    @Autowired
    Scheduler scheduler;

    private final static String PREFIX="-";

    @Override
    public NacosJob getById(Long id) {
        return nacosJobDao.selectById(id);
    }

    @Override
    public Integer scheduleJob(NacosJob job) throws SchedulerException {
        log.info("[设定任务]：{}", job);
        JobDetail jobDetail = JobBuilder.newJob(NacosJobDetail.class).build();
        Trigger trigger = TriggerBuilder.newTrigger()
                .usingJobData(JobDataKey.JOB.toString(), JSONUtil.toJsonStr(job))
                .withSchedule(CronScheduleBuilder.cronSchedule(job.getCron()))
                .withIdentity(job.getPath(), job.getNamespaceId()+PREFIX+job.getGroupName()+PREFIX+job.getServiceName())
                .build();
        scheduler.scheduleJob(jobDetail, trigger);
        job.setStatus(JOB_STATUS.RUNNING.getCode());
        job.setUpdateTime(new Date());
        return nacosJobDao.updateById(job);
    }

    @Override
    public List<NacosJob> list(NacosJob job) {
        QueryWrapper<NacosJob> queryWrapper = new QueryWrapper(job);
        return nacosJobDao.selectList(queryWrapper);
    }

    @Override
    public Integer unschedule(NacosJob job) throws SchedulerException {
        log.info("[取消任务]：{}", job);
        scheduler.unscheduleJob(TriggerKey.triggerKey(job.getPath(),job.getNamespaceId()+PREFIX+job.getGroupName()+PREFIX+job.getServiceName()));
        job.setStatus(JOB_STATUS.STOP.getCode());
        job.setUpdateTime(new Date());
        return nacosJobDao.updateById(job);
    }

    @Override
    public Integer addJob(NacosJob job) {
        job.setIsDelete(0);
        job.setStatus(JOB_STATUS.REDAY.getCode());
        job.setCreateTime(new Date());
        return nacosJobDao.insert(job);
    }
}